package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.enums.SysPermissionEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.vo.dict.DictAreaVO;
import com.bifang.module.base.common.vo.dict.SelectVO;
import com.bifang.module.base.common.vo.operationPeriod.OperationCurVO;
import com.bifang.module.base.common.vo.operationPeriod.OperationPeriodVO;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.base.core.integration.DictIntegration;
import com.bifang.module.base.core.integration.OperationPeriodIntegration;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.SchoolDictEnum;
import com.jwsoft.manager.common.vo.eduAppointSchool.EduAppointSchoolKeyVO;
import com.jwsoft.manager.common.vo.eduAppointSchool.EduAppointSchoolQueryVO;
import com.jwsoft.manager.common.vo.eduAppointSchool.EduAppointSchoolVO;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolQueryVO;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolVO;
import com.jwsoft.manager.core.dao.model.EduAppointSchool;
import com.jwsoft.manager.core.dao.service.EduAppointSchoolService;
import com.jwsoft.manager.core.dao.service.EduSchoolService;
import com.jwsoft.manager.core.integration.EduAppointSchoolIntegration;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 城区E学校维护表业务实现类
 *
 * @author hhj
 * @since 2022-12-19
 */
@ApiService(funcCode = "eduAppointSchool", title = "城区E学校维护表")
public class EduAppointSchoolIntegrationImpl implements EduAppointSchoolIntegration {

    @Autowired
    public EduAppointSchoolService eduAppointSchoolService;

    @Autowired
    private DictHelper dictHelper;
    @Autowired
    private EduHelper eduHelper;

    @Resource
    private OperationPeriodIntegration operationPeriodIntegration;

    @Autowired
    private DictIntegration dictIntegration;

    @Autowired
    private EduSchoolService eduSchoolService;

    @Override
    @OpApi(funcCode = "eduAppointSchool0100", title = "获取小学学校信息", funcType = FuncTypeEnum.query,
            checkPrivilege = BoolEnum.FALSE,
            publicFlag = BoolEnum.TRUE)
    public PageInfo<EduSchoolVO> getPrimarySchoolList(EduSchoolQueryVO vo) {
        if (!ObjectUtils.isEmpty(vo.getShortName())) {
            vo.setSchoolName(vo.getShortName());
        }
        vo.setShortName("");
        vo.setSchoolCategory("2");

        //查询学校信息
        List<EduSchoolVO> eduSchoolList = querySchoolInfo(vo);
        if (CollectionUtils.isEmpty(eduSchoolList)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduSchoolVO> pageInfo = new PageInfo<>(eduSchoolList);
        List<EduSchoolVO> resList = pageInfo.getList();
//        if (SpecialStringUtils.equals(
//                SessionUtil.getSessionInfo().getEquipmentType(),
//                EquipmentTypeEnum.APP.getType())) {
//            if (resList.size() > 0) {
//                List<String> orgIdList =
//                        resList.stream().map(SchoolVO::getOrgId).collect(Collectors.toList());
//                QueryWrapper<EduEnrollmenBrochure> brochureQueryWrapper = new QueryWrapper<>();
//                brochureQueryWrapper.lambda().in(EduEnrollmenBrochure::getSchoolId, orgIdList);
//                List<EduEnrollmenBrochure> brochureList =
//                        eduEnrollmenBrochureService.list(brochureQueryWrapper);
//                QueryWrapper<EduSchoolConfig> schoolConfigQueryWrapper = new QueryWrapper<>();
//                schoolConfigQueryWrapper
//                        .lambda()
//                        .in(EduSchoolConfig::getSchoolId, orgIdList)
//                        .eq(EduSchoolConfig::getAuthStatus, AuthStatusEnum.YES.getType())
//                        .eq(EduSchoolConfig::getStatus,BoolEnum.TRUE.getType());
//                List<SchoolConfigVO> allConfigList =
//                        Convert.toList(
//                                SchoolConfigVO.class,
//                                eduSchoolConfigService.list(schoolConfigQueryWrapper));
//                resList.forEach(
//                        item -> {
//                            int year;
//                            EduEnrollmenBrochure brochure =
//                                    brochureList.stream()
//                                            .filter(
//                                                    item1 ->
//                                                            SpecialStringUtils.equals(
//                                                                    item1.getSchoolId(),
//                                                                    item.getOrgId()))
//                                            .sorted(
//                                                    Comparator.comparingInt(
//                                                            EduEnrollmenBrochure::getYear)
//                                                            .reversed())
//                                            .collect(Collectors.toList())
//                                            .get(0);
//                            if (ObjectUtils.isEmpty(brochure)) {
//                                item.setHasEnrollFlag(false);
//                                return;
//                            } else {
//                                item.setHasEnrollFlag(true);
//                                year = brochure.getYear();
//                            }
//                            List<SchoolConfigVO> configList =
//                                    allConfigList.stream()
//                                            .filter(
//                                                    item1 ->
//                                                            item1.getYear() == year
//                                                                    && SpecialStringUtils.equals(
//                                                                    item1.getSchoolId(),
//                                                                    item.getOrgId()))
//                                            .collect(Collectors.toList());
//                            int stopNum = 0;
//                            long curTime = DateUtil.currentSeconds();
//                            if (configList.size() > 0) {
//                                Date startTime = configList.get(0).getStartTime();
//                                Date endTime = configList.get(0).getEndTime();
//                                for (int i = 0; i < configList.size(); i++) {
//                                    long startT = configList.get(i).getStartTime().getTime() / 1000;
//                                    long endT = configList.get(i).getEndTime().getTime() / 1000;
//                                    if (DateUtil.compare(
//                                            startTime, configList.get(i).getStartTime())
//                                            > 0) {
//                                        startTime = configList.get(i).getStartTime();
//                                    }
//                                    if (DateUtil.compare(endTime, configList.get(i).getEndTime())
//                                            < 0) {
//                                        endTime = configList.get(i).getEndTime();
//                                    }
//                                    if (DateUtil.compare(
//                                            configList.get(i).getEndTime(), DateUtil.date())
//                                            < 0) {
//                                        stopNum++;
//                                        configList
//                                                .get(i)
//                                                .setEnrollStatus(EnrollStatusEnum.finish.getType());
//                                    } else {
//                                        if (curTime < startT) {
//                                            configList
//                                                    .get(i)
//                                                    .setEnrollStatus(
//                                                            EnrollStatusEnum.wait.getType());
//                                        } else if (curTime > endT) {
//                                            configList
//                                                    .get(i)
//                                                    .setEnrollStatus(
//                                                            EnrollStatusEnum.finish.getType());
//                                        } else {
//                                            configList
//                                                    .get(i)
//                                                    .setEnrollStatus(EnrollStatusEnum.on.getType());
//                                        }
//                                    }
//                                }
//
//                                if (stopNum == configList.size()) {
//                                    item.setEnrollStatus(EnrollStatusEnum.finish.getType());
//                                } else {
//                                    long startT = startTime.getTime() / 1000;
//                                    long endT = endTime.getTime() / 1000;
//                                    if (curTime < startT) {
//                                        item.setEnrollStatus(EnrollStatusEnum.wait.getType());
//                                    } else if (curTime > endT) {
//                                        item.setEnrollStatus(EnrollStatusEnum.finish.getType());
//                                    } else {
//                                        item.setEnrollStatus(EnrollStatusEnum.on.getType());
//                                    }
//                                }
//                                item.setStartTime(startTime);
//                                item.setEndTime(endTime);
//                                dictUtil.valueToName(
//                                        configList, Arrays.asList(SchoolConfigDictEnum.values()));
//                                item.setConfigList(configList);
//                            }
//                        });
//            }
//        }

        // 转义数据字典值
        dictHelper.valueToName(resList, Arrays.asList(SchoolDictEnum.values()));

        return PagerUtil.parsePagerVo(resList, pageInfo);
    }

    @Override
    @OpApi(
            funcCode = "eduAppointSchool0101",
            title = "获取初中学校信息",
            funcType = FuncTypeEnum.query,
            checkPrivilege = BoolEnum.FALSE,
            publicFlag = BoolEnum.TRUE)
    public PageInfo<EduSchoolVO> getJuniorSchoolList(EduSchoolQueryVO vo) {
        if (!ObjectUtils.isEmpty(vo.getShortName())) {
            vo.setSchoolName(vo.getShortName());
        }
        vo.setShortName("");
        vo.setSchoolCategory("3");

        //查询学校信息
        List<EduSchoolVO> eduSchoolList = querySchoolInfo(vo);
        if (CollectionUtils.isEmpty(eduSchoolList)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduSchoolVO> pageInfo = new PageInfo<>(eduSchoolList);
        List<EduSchoolVO> resList = pageInfo.getList();
//        if (SpecialStringUtils.equals(
//                SessionHelper.getSessionInfo().getEquipmentType(),
//                EquipmentTypeEnum.APP.getType())) {
//            if (resList.size() > 0) {
//                List<String> orgIdList =
//                        resList.stream().map(SchoolVO::getOrgId).collect(Collectors.toList());
//                QueryWrapper<EduEnrollmenBrochure> brochureQueryWrapper = new QueryWrapper<>();
//                brochureQueryWrapper.lambda().in(EduEnrollmenBrochure::getSchoolId, orgIdList);
//                List<EduEnrollmenBrochure> brochureList =
//                        eduEnrollmenBrochureService.list(brochureQueryWrapper);
//                QueryWrapper<EduSchoolConfig> schoolConfigQueryWrapper = new QueryWrapper<>();
//                schoolConfigQueryWrapper
//                        .lambda()
//                        .in(EduSchoolConfig::getSchoolId, orgIdList)
//                        .eq(EduSchoolConfig::getAuthStatus,AuthStatusEnum.YES.getType())
//                        .eq(EduSchoolConfig::getStatus,BoolEnum.TRUE.getType());
//                List<SchoolConfigVO> allConfigList =
//                        Convert.toList(
//                                SchoolConfigVO.class,
//                                eduSchoolConfigService.list(schoolConfigQueryWrapper));
//                resList.forEach(
//                        item -> {
//                            int year;
//                            EduEnrollmenBrochure brochure =
//                                    brochureList.stream()
//                                            .filter(
//                                                    item1 ->
//                                                            SpecialStringUtils.equals(
//                                                                    item1.getSchoolId(),
//                                                                    item.getOrgId()))
//                                            .sorted(
//                                                    Comparator.comparingInt(
//                                                            EduEnrollmenBrochure::getYear)
//                                                            .reversed())
//                                            .collect(Collectors.toList())
//                                            .get(0);
//                            if (ObjectUtils.isEmpty(brochure)) {
//                                item.setHasEnrollFlag(false);
//                                return;
//                            } else {
//                                item.setHasEnrollFlag(true);
//                                year = brochure.getYear();
//                            }
//                            List<SchoolConfigVO> configList =
//                                    allConfigList.stream()
//                                            .filter(
//                                                    item1 ->
//                                                            item1.getYear() == year
//                                                                    && SpecialStringUtils.equals(
//                                                                    item1.getSchoolId(),
//                                                                    item.getOrgId()))
//                                            .collect(Collectors.toList());
//                            int stopNum = 0;
//                            long curTime = DateUtil.currentSeconds();
//                            if (configList.size() > 0) {
//                                Date startTime = configList.get(0).getStartTime();
//                                Date endTime = configList.get(0).getEndTime();
//                                for (int i = 0; i < configList.size(); i++) {
//                                    long startT = configList.get(i).getStartTime().getTime() / 1000;
//                                    long endT = configList.get(i).getEndTime().getTime() / 1000;
//                                    if (DateUtil.compare(
//                                            startTime, configList.get(i).getStartTime())
//                                            > 0) {
//                                        startTime = configList.get(i).getStartTime();
//                                    }
//                                    if (DateUtil.compare(endTime, configList.get(i).getEndTime())
//                                            < 0) {
//                                        endTime = configList.get(i).getEndTime();
//                                    }
//                                    if (DateUtil.compare(
//                                            configList.get(i).getEndTime(), DateUtil.date())
//                                            < 0) {
//                                        stopNum++;
//                                        configList
//                                                .get(i)
//                                                .setEnrollStatus(EnrollStatusEnum.finish.getType());
//                                    } else {
//                                        if (curTime < startT) {
//                                            configList
//                                                    .get(i)
//                                                    .setEnrollStatus(
//                                                            EnrollStatusEnum.wait.getType());
//                                        } else if (curTime > endT) {
//                                            configList
//                                                    .get(i)
//                                                    .setEnrollStatus(
//                                                            EnrollStatusEnum.finish.getType());
//                                        } else {
//                                            configList
//                                                    .get(i)
//                                                    .setEnrollStatus(EnrollStatusEnum.on.getType());
//                                        }
//                                    }
//                                }
//
//                                if (stopNum == configList.size()) {
//                                    item.setEnrollStatus(EnrollStatusEnum.finish.getType());
//                                } else {
//                                    long startT = startTime.getTime() / 1000;
//                                    long endT = endTime.getTime() / 1000;
//                                    if (curTime < startT) {
//                                        item.setEnrollStatus(EnrollStatusEnum.wait.getType());
//                                    } else if (curTime > endT) {
//                                        item.setEnrollStatus(EnrollStatusEnum.finish.getType());
//                                    } else {
//                                        item.setEnrollStatus(EnrollStatusEnum.on.getType());
//                                    }
//                                }
//                                item.setStartTime(startTime);
//                                item.setEndTime(endTime);
//                                dictUtil.valueToName(
//                                        configList, Arrays.asList(SchoolConfigDictEnum.values()));
//                                item.setConfigList(configList);
//                            }
//                        });
//            }
//        }

        // 转义数据字典值
        dictHelper.valueToName(resList, Arrays.asList(SchoolDictEnum.values()));

        return PagerUtil.parsePagerVo(resList,pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduAppointSchool0001", title = "城区E学校维护表分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<EduAppointSchoolVO> getList(EduAppointSchoolQueryVO vo) {
        EduAppointSchoolVO eduAppointSchoolVO = new EduAppointSchoolVO();
        if (vo.getNewSchoolId() != null || vo.getNewSchoolId() != "") {
            eduAppointSchoolVO.setNewSchoolId(vo.getNewSchoolId());
        }
        if (vo.getOldSchoolId() != null || vo.getOldSchoolId() != "") {
            eduAppointSchoolVO.setOldSchoolId(vo.getOldSchoolId());
        }
        if (vo.getAreaCode() != null || vo.getAreaCode() != "") {
            eduAppointSchoolVO.setAreaCode(vo.getAreaCode());
        }
        if (vo.getYear() != null) {
            eduAppointSchoolVO.setYear(vo.getYear());
        }
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());

        List<EduAppointSchoolVO> eduAppointSchoolVOList =
                eduAppointSchoolService.selectEduAppointSchoolList(eduAppointSchoolVO);
        if (CollectionUtils.isEmpty(eduAppointSchoolVOList)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduAppointSchoolVO> pageInfo = new PageInfo<>(eduAppointSchoolVOList);
        List<EduAppointSchoolVO> resList = pageInfo.getList();
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
//        List<EduAppointSchoolVO> resultList = Convert.toList(EduAppointSchoolVO.class, pageInfo.getList());
        // 转义数据字典值
        dictHelper.valueToName(resList, Arrays.asList(SchoolDictEnum.values()));
        return PagerUtil.parsePagerVo(resList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduAppointSchool0002", title = "城区E学校维护表根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduAppointSchoolVO getById(EduAppointSchoolKeyVO vo) {
        EduAppointSchool entity = eduAppointSchoolService.getById(vo.getAppointSchoolId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduAppointSchoolVO result = Convert.convert(EduAppointSchoolVO.class, entity);
        return result;
    }

    /**
     * 保存前统一校验
     */
    @Override
    @OpApi(funcCode = "eduAppointSchool0003", title = "城区E学校维护表保存前校验", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduAppointSchoolVO vo) {
        //主键为空为新增校验

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "eduAppointSchool0004", title = "城区E学校维护表新增", funcType = FuncTypeEnum.insert)
    @Transactional
    public EduAppointSchoolVO add(EduAppointSchoolVO vo) {
        //保存前校验
        checkSave(vo);
        if (StringUtils.isBlank(vo.getAreaCode())) {
            vo.setAreaCode(SessionUtil.getAreaCode());
        }
        if (vo.getYear() == null) {
            vo.setYear(eduHelper.thisYear());
        }
        //保存数据
        // 查找小学是否已存在
        QueryWrapper<EduAppointSchool> eduAppointSchoolQueryWrapper1 =
                new QueryWrapper<>();
        eduAppointSchoolQueryWrapper1.lambda().eq(EduAppointSchool::getOldSchoolId, vo.getOldSchoolId())
                .eq(EduAppointSchool::getNewSchoolId, vo.getNewSchoolId())
                .eq(EduAppointSchool::getYear, vo.getYear());

        List<EduAppointSchool> list1 = eduAppointSchoolService.list(eduAppointSchoolQueryWrapper1);
        if (list1.size() > 0) {
            throw new AppException("该小学对应初中已存在！");
        }

        // 添加
        vo.setAppointSchoolId(IdUtil.simpleUUID());
        EduAppointSchool eduAppointSchool5 = Convert.convert(EduAppointSchool.class, vo);
        try {
            eduAppointSchoolService.save(eduAppointSchool5);
        } catch (Exception e) {
            throw new AppException("添加失败！");
        }

        //将主键设置回vo使操作日志可以取到
        vo.setAppointSchoolId(eduAppointSchool5.getAppointSchoolId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduAppointSchool0005", title = "城区E学校维护表修改", funcType = FuncTypeEnum.update)
    @Transactional
    public EduAppointSchoolVO edit(EduAppointSchoolVO vo) {
        if (ObjectUtils.isEmpty(vo.getAppointSchoolId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduAppointSchool oldEntity = eduAppointSchoolService.getById(vo.getAppointSchoolId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduAppointSchool entity = Convert.convert(EduAppointSchool.class, vo);
        eduAppointSchoolService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduAppointSchool0006", title = "城区E学校维护表根据主键删除", funcType = FuncTypeEnum.delete)
    @Transactional
    public void del(EduAppointSchoolKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getAppointSchoolId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduAppointSchool entity = eduAppointSchoolService.getById(vo.getAppointSchoolId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduAppointSchoolService.removeById(vo.getAppointSchoolId());
    }

    private List<EduSchoolVO> querySchoolInfo(EduSchoolQueryVO vo) {
        boolean permissionFlag = true;
        if (vo.getPermissionFlag() != null) {
            permissionFlag = vo.getPermissionFlag();
        }
        if (!ObjectUtils.isEmpty(vo.getSearchText())) {
            vo.setSchoolName(vo.getSearchText());
        }
        if (!ObjectUtils.isEmpty(vo.getSchoolCategory())) {
            vo.setSchoolCategory(vo.getSchoolCategory());
        }
        Map<String, Object> queryMap = BeanUtil.beanToMap(vo, false, true);
        Set<String> systemPrivileges = SessionUtil.getSystemPrivileges();
        if (!permissionFlag
                || systemPrivileges.contains(SysPermissionEnum.allorg.getType())
                || systemPrivileges.contains(SysPermissionEnum.superadmin.getType())) {

        } else {
            //查出账号配置的行政区划及子级行政区划
            List<SelectVO> districtByOrg = dictIntegration.getDistrictByOrg(new DictAreaVO());
            List<String> areaList = districtByOrg.stream().map(SelectVO::getDictKey).collect(Collectors.toList());
            areaList.add(SessionUtil.getAreaCode());
            if (areaList.size() >0 ){
                queryMap.put("areaList",areaList);
            }
        }
        int year = 0;
        OperationCurVO curVO = new OperationCurVO();
        curVO.setOperating("XN");
        OperationPeriodVO operationPeriodVO =
                operationPeriodIntegration.getCurrentByOperating(curVO);
        if (operationPeriodVO != null) {
            year = operationPeriodVO.getPeriodYear();
        } else {
            year = DateUtil.thisYear();
        }
        if (!ObjectUtils.isEmpty(vo.getCheckBrochure()) && vo.getCheckBrochure()) {
            queryMap.put("year", year);
        }

        // 开启分页
        if (vo.getPageNum() != null && vo.getPageSize() != null) {
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        }
        return eduSchoolService.selectSchoolList(queryMap);
    }
}
